﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml;
using System.Xml.Serialization;
using bmapi.HelperClass;
using bmapi.Models.CADModel;
using bmapi.Models.DataEntity;
using bmapi.SQLServerAccess;

namespace bmapi.Controllers
{
    public class CAD33Controller : CADFinishController
    {
        /// <summary>
        /// 导入生产单   
        /// </summary> 
        /// <param name="json">id process go upload file文件名/文件夹名 extname扩展名  TDxml文件路径 </param>
        [HttpPost, Route("cad33/Finish")]
        public string Finish(dynamic json)
        {
            WriteDebug("cad33/Finish","1");
            if (json==null)
                return ReturnError(201, "没有可执行参数");
            string filename = json.file.ToString();
            int upload =Convert.ToInt32(json.upload);            

            int loginid = GetCrrentIDByToken();
            User user = GetUserByLoginID(loginid);

            WriteDebug("cad33/Finish", "2");

            if (user==null)
                return ReturnError(201, "不存在当前工号为"+loginid+"的用户");

            string xmlpath = GetPCPath(json.name.ToString()) + "\\" + filename;

            WriteDebug("cad33/Finish", "3");

            if (!File.Exists(xmlpath))
                return ReturnError(201, "找不到路径" + xmlpath);

            #region  读取xml文件数据 样式名，订单号，ERP中的ID(orderId),生产件数
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlpath);

            WriteDebug("cad33/Finish", "4");

            string modelName = doc.GetElementsByTagName("modelName")[0].InnerText;
            string orderName = doc.GetElementsByTagName("orderName")[0].InnerText;
            XmlNodeList xmllist = doc.GetElementsByTagName("orderID");
            string orderId = "";
            if (xmllist.Count>0)
                orderId = xmllist[0].InnerText;            
            int number = Convert.ToInt32(doc.GetElementsByTagName("number")[0].InnerText);

            WriteDebug("cad33/Finish", "5");

            #endregion

            if (string.IsNullOrEmpty(modelName) || string.IsNullOrEmpty(orderName) || number<0)
                return ReturnError(201, "给的数据不完整,样式名:"+modelName+"，订单号:"+orderName+"，ERP中的ID:"+orderId+",生产件数:"+number);
            WriteDebug("cad33/Finish", "6");
            if (CheckOrdername(orderName))
                return ReturnError(201, orderName+"该生产单号已经存在");
            else
                if (AddOrderAndPC(user, modelName, orderName, orderId, number) == 0)
                    return ReturnError(201, "数据操作出错");           
            return ReturnError(200, "OK");
        }

        /// <summary>
        /// 添加生产单信息 
        /// </summary> 
        /// <param name="loginid"></param>
        /// <param name="modelName"></param>
        /// <param name="orderName"></param>
        /// <param name="orderID"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        private int AddOrderAndPC(User user, string modelName, string orderName, string orderID, int number)
        {
            try
            {
                string sql = "";
                List<SQLCommand> cmds = new List<SQLCommand>();
                int id = GetNewSafeID(user.login_id);
                if (user == null)
                    return 0;
                #region  新增订单   
                SQLCommand sc = new SQLCommand("select id from Model_tb where name=@name", "@name", modelName);
                int modelid = Convert.ToInt32(sc.ExecuteScalar());
                
                //PLID是当前用户对应的吗  暂时这样做处理  model_id 根据样板名从Model_tb表中获取 erpid为表中的orderID ername样板名 lsh流水号暂认为0
                //流水号  LSH LSH_tb中erpID指用户id即工号 根据用户id获取流水号
                sql = "insert into Order_tb values(@id,@name,@createid,@createtime,@finishtime,@plid,@modelid,0,' ',@erpid,@erpname,' ',' ',0,0,0,@lsh,0,@number,1)";
                sc = new SQLCommand(sql);
                sc.Add("@id", id);
                sc.Add("@name", orderName);
                sc.Add("@createid", user.login_id);
                sc.Add("@createtime", DateTime.Now);
                sc.Add("@finishtime", DateTime.Now.AddMonths(2));
                sc.Add("@plid", user.PLID);
                sc.Add("modelid", modelid);
                sc.Add("@erpid", orderID);
                sc.Add("@erpname", modelName);
                sc.Add("@lsh", 0);
                sc.Add("@number", number);
                cmds.Add(sc);
                #endregion
                #region  添加流程
                sql = "insert into PC_tb(path,pc_id,PLID,maxStep,step, model_id) values(@path,@pcid,@plid,@maxstep,@step, @model_id)";
                sc = new SQLCommand(sql);
                sc.Add("@path", orderName);
                sc.Add("@pcid", id);
                sc.Add("@plid", user.PLID);
                sc.Add("@maxstep", user.code);
                sc.Add("@step", GetNextProcessID(user.PLID, user.code));
                sc.Add("@model_id", modelid);
                cmds.Add(sc);
                #endregion
                return SQLCommand.ExecTran(cmds);
            }
            catch (Exception e)
            {

                WriteLog("AddOrderAndPC", e.Message);
                return 0;
            }
           
        }

        private void MoveToWork(string extnmae,string userpath,string workpath,string ordername,string filename)
        {
            string orderpath = workpath + "\\" + ordername;
            if (!Directory.Exists(orderpath))
                Directory.CreateDirectory(orderpath);
            //移动文件/文件夹  
            if (extnmae == "") //移动文件
                Directory.Move(userpath + "\\" + filename, orderpath + filename);
            else
            {
                string filedir = null;
                DirectoryInfo xmlDir = new DirectoryInfo(userpath);
                foreach (var item in xmlDir.GetDirectories())
                {
                    if (item.Name.Contains(filename))
                    {
                        filedir = item.FullName;
                        break; //说明有文件夹   
                    }
                }
                if (filedir != null)  //有文件还有文件夹  
                {
                    Directory.Move(userpath + "\\" + filename, orderpath + "\\" + filename);
                    File.Move(userpath + "\\" + filename + ".xml", orderpath + "\\" + filename + ".xml");
                }
                else //只有文件
                {
                    File.Move(userpath + "\\" + filename + ".xml", orderpath + "\\" + filename + ".xml");
                }
            }
        }

    }
}
